package com.hoas.api.config;

import com.hoas.api.core.entity.UserToken;
import com.hoas.api.core.intf.TokenStorage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

public class RedisTokenStorage implements TokenStorage {

    @Resource( name = "redisTemplate")
    private RedisTemplate<String, String>  tokenRels;

    @Resource( name = "redisTemplate")
    private RedisTemplate<String, UserToken>  accessTokenRel;

    @Override
    public void storageToken(UserToken token,long timeout) {

        tokenRels.opsForValue().set(token.getRefreshToken(), token.getAccessToken());
        accessTokenRel.opsForValue().set(token.getAccessToken(),token);

        tokenRels.expire(token.getRefreshToken(), timeout, TimeUnit.MINUTES);
        accessTokenRel.expire(token.getAccessToken(), timeout, TimeUnit.MINUTES);

    }

    @Override
    public String getAccessToken(String refreshToken) {
        return tokenRels.opsForValue().get(refreshToken);
    }

    @Override
    public UserToken getUserToken(String accessToken) {
        return accessTokenRel.opsForValue().get(accessToken);
    }

    @Override
    public void removeStorage(String accessToken) {
        accessTokenRel.delete(accessToken);
        tokenRels.delete(accessToken);
    }
}
